import {Injectable} from '@angular/core';
import {AppConfig} from '../config';
import {Headers, Http} from '@angular/http';
import {Device} from '../entity/device.model';
import {Observable} from 'rxjs/Observable';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class DeviceService {
  private param = 'devices';

  private get url(): string {
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  constructor(private http: InterceptorService) {
  }

  //查询设备列表
  getDevices(): Promise<Device[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  //查询设备列表
  getDevicesByCategoryCode(id: number): Promise<Device[]> {
    return this.http.get(`${this.url}/categoryId/${id}`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  //通过风场Id和工期Id查询设备列表
  getDevicesByFarmIdPhaseId(farmId: number, phaseId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/phase/${phaseId}`)
      .toPromise()
      .then(response => {
        return response.data as Device[];
      })
      .catch(this.handleError);
  }

  getDevicesByFarmIdDeviceCategoryCode(farmId: number, deviceCategoryCode: String): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/deviceCategoryCode/${deviceCategoryCode}`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  getDevicesByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  getTurbinesByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/trubines`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  //根据farmId获取箱变设备
  getBoxSubstationsByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/boxsubstations`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  getACCabinetsByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/accabinets`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  getDCCabinetsByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/dccabinets`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  // 根据风场Id查询逆变器设备
  getInvertersByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/inverters`)
      .toPromise()
      .then(response => {
        return response.data as Device[]
      })
      .catch(this.handleError);
  }

  // 根据风场Id查询汇流箱
  getConvergenceBoxsByFarmId(farmId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/farm/${farmId}/convergenceboxs`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  // 根据型号ID查询设备
  getDeviceByModelId(modelId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/model/${modelId}`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  // 根据型号ID查询设备
  getDeviceByParentId(parentId: number): Promise<Device[]> {
    return this.http.get(`${this.url}/parent/${parentId}`)
      .toPromise()
      .then(response => response.data as Device[])
      .catch(this.handleError);
  }

  create(device: Device): Promise<Device> {
    // const url = `http://192.168.15.150:8585/webapi/v1/devices `;
    return this.http.post(this.url, JSON.stringify(device))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Device;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
      .catch(this.handleError);
  }

  update(device: Device): Promise<Device> {
    const url = `${this.url}`;
    // const url = `http://192.168.15.150:8585/webapi/v1/devices `;
    return this.http.put(url, JSON.stringify(device))
      .toPromise()
      .then(() => device)
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  batchDelete(valueIds: number[]): Promise<any> {
    const apiUrl = `${this.url}?items=${valueIds}`;
    return this.http.delete(apiUrl)
      .toPromise()
      .then(response => {
        try {
          let result = response;
          switch (result.code) {
            case '200':
              return result;
            case '-1':
              throw new Error(result.message);
            case '8001':
              return result;
          }
        }
        catch (error) {
          throw error;
        }

      })
      .catch(this.handleError);
  }


  //根据deviceCode 判断是否已经存在
  hasDeviceCode(deviceCode: string, deviceId: number, farmId: number, deviceCategoryId: number): Observable<boolean> {

    const url = `${this.url}/deviceCode/${deviceCode}/deviceId/${deviceId}/farmId/${farmId}/deviceCategoryId/${deviceCategoryId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }


  //根据deviceName 判断是否已经存在
  hasDeviceName(deviceName: string, deviceId: number, farmId: number, deviceCategoryId: number): Observable<boolean> {
    deviceName = `${deviceName}`;
    let devName = deviceName.replace(/^#/, '%23')
    const url = `${this.url}/deviceName/${devName}/deviceId/${deviceId}/farmId/${farmId}/deviceCategoryId/${deviceCategoryId}`;
    return this.http.get(url).map(response => {
      let code = response.code;
      switch (code) {
        case '3001':
          return true;
        case '3002':
          return false;
      }
    }).catch(this.handleError);
  }


  private handleError(error: any): Promise<any> {
    // console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }
}


